<template>
  <div class="option-wrapper">
    <div class="option-main">
      <a-form layout="vertical" :model="formState" :rules="rules">
        <div class="option-column">
          <div class="column-title">实验器材基础信息</div>
          <div class="column-content">
            <div class="content-item">
              <a-form-item label="名称" name="name">
                <a-input
                  v-model:value="formState.name"
                  placeholder="请输入名称"
                />
              </a-form-item>
            </div>
            <!-- <div class="content-item">
              <a-form-item label="设备保修期" name="limt">
                <a-input
                  v-model:value="formState.limt"
                  placeholder="请输入设备保修期"
                  suffix="个月"
                />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="设备型号" name="no">
                <a-input
                  v-model:value="formState.no"
                  placeholder="请输入设备型号"
                />
              </a-form-item>
            </div> -->
            <div class="content-item">
              <a-form-item label="分类" name="equipment_category_id">
                <a-select
                  v-model:value="formState.equipment_category_id"
                  placeholder="请选择分类"
                >
                  <a-select-option
                    v-for="option in equipmentOptions"
                    :key="option.value"
                    :value="option.value"
                  >
                    {{ option.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </div>
            <!-- <div class="content-item">
              <a-form-item label="最新软件版本" name="version">
                <a-input
                  v-model:value="formState.version"
                  placeholder="请输入最新软件版本"
                />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="设备编码" name="code">
                <a-input
                  v-model:value="formState.code"
                  placeholder="请输入设备编码"
                />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="设备品牌" name="brand">
                <a-input
                  v-model:value="formState.brand"
                  placeholder="请输入设备品牌"
                />
              </a-form-item>
            </div> -->
          </div>
        </div>
        <div class="option-column">
          <div class="column-title">器材模型</div>
          <a-upload-dragger
            v-model:fileList="fileList1"
            name="file"
            :multiple="false"
            :max-count="1"
            :customRequest="customUpload1"
            @change="handleChange1"
            @drop="handleDrop1"
          >
            <p class="ant-upload-drag-icon">
              <CloudUploadOutlined />
            </p>
            <p class="ant-upload-hint">
              将模型拖拽到此，或单击<span class="blue">直接上传</span>
            </p>
          </a-upload-dragger>
        </div>
        <div class="option-column">
          <div class="column-title">预览图片</div>
          <a-upload-dragger
            v-model:fileList="fileList2"
            name="file"
            :multiple="false"
            :max-count="1"
            :customRequest="customUpload2"
            @change="handleChange2"
            @drop="handleDrop2"
          >
            <p class="ant-upload-drag-icon">
              <CloudUploadOutlined />
            </p>
            <p class="ant-upload-hint">
              将jpg、bmp、png格式的图片拖拽到此，或单击<span class="blue"
                >直接上传</span
              >分辨建议为400*300
            </p>
          </a-upload-dragger>
        </div>
        <div class="option-column">
          <div class="column-title">仪器介绍</div>
          <edit v-model:value="introduction" />
        </div>
        <!-- <div class="option-column">
          <div class="column-title">实验内容</div>
          <edit v-model:value="content" />
        </div>
        <div class="option-column">
          <div class="column-title">配置参数</div>
          <div
            class="column-content"
            v-for="(item, index) in configurationList"
          >
            <div class="content-item">
              <a-form-item label="配置名称" name="configurationName">
                <a-input
                  v-model:value="item.configurationName"
                  placeholder="请输入配置名称"
                />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="配置参数" name="configurationParameter">
                <a-input
                  v-model:value="item.configurationParameter"
                  placeholder="请输入配置参数"
                />
              </a-form-item>
              <MinusCircleOutlined
                v-if="configurationList.length > 1"
                class="delete-button"
                @click="deleteDevice(index)"
              />
            </div>
          </div>
          <div class="column-footer">
            <a-button type="dashed" :icon="h(PlusOutlined)" @click="addDevice"
              >添加设备</a-button
            >
          </div>
        </div> -->
        <!-- <div class="option-column">
          <div class="column-title">备注</div>
          <div class="column-content">
            <a-form-item label="备注信息" name="remark">
              <a-textarea
                v-model:value="formState.remark"
                placeholder="请输入备注信息"
                :rows="3"
              />
            </a-form-item>
          </div>
        </div>
        <div class="option-column">
          <div class="column-title">报修二维码</div>
          <div class="column-content">
            <p>创建设备后自动生成</p>
          </div>
        </div> -->
        <div class="option-footer">
          <a-button class="opt-btn" @click="resetForm">取消</a-button>
          <a-button
            class="opt-btn"
            type="primary"
            @click="handleSubmit"
            :loading="submitLoading"
            >保存</a-button
          >
        </div>
      </a-form>
    </div>
  </div>
</template>
<script setup>
import { ref, computed, h, watch, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { message } from "ant-design-vue";
import {
  PlusOutlined,
  MinusCircleOutlined,
  CloudUploadOutlined,
} from "@ant-design/icons-vue";
import edit from "@/components/edit/index.vue";
import administratorApi from "@/api/administrator";
import systemApi from "@/api/system";

const router = useRouter();
const route = useRoute();

const formState = ref({
  name: "",
  limt: "",
  no: "",
  status: "enabled",
  version: "",
  model: "",
  code: "",
  brand: "",
  equipment_category_id: null,
  enabled: true,
  remark: "",
});

const isEdit = ref(false);
const equipmentId = ref(null);

// 初始化数据
onMounted(() => {
  getEquipmentOptions();
  // 检查是否为编辑模式
  if (route.query.equipment_id) {
    isEdit.value = true;
    equipmentId.value = route.query.equipment_id;
    fetchEquipmentDetail();
    // 初始化加载设备选项
  }
});

// 获取设备详情
const fetchEquipmentDetail = async () => {
  try {
    const response = await administratorApi.ExperimentEquipmentFetchModel({
      experiment_id: route.query.experiment_id,
      equipment_id: equipmentId.value,
    });

    console.log("设备详情API响应:", response);

    if (response) {
      // 检查是否有嵌套的equipment对象
      const data = response.equipment || response;
      
      console.log("设备分类ID:", data.equipment_category_id, "设备分类名称:", data.equipment_category_name);
      
      formState.value = {
        name: data.name || "",
        limt: data.warranty_period || "",
        no: data.model || "",
        status: data.enabled ? "enabled" : "disabled",
        version: data.software_version || "",
        model: data.model || "",
        code: data.code || "",
        brand: data.brand || "",
        equipment_category_id: data.equipment_category_id,
        enabled: data.enabled || true,
        remark: data.remark || "",
      };
      
      console.log("表单设置完成，分类ID:", formState.value.equipment_category_id);

      // 设置富文本内容
      introduction.value = data.introduce || "";
      content.value = data.experiment_content || "";

      // 设置配置参数
      if (data.configuration_parameters) {
        try {
          configurationList.value = JSON.parse(
            data.configuration_parameters
          );
        } catch (e) {
          console.error("解析配置参数失败:", e);
        }
      }

      // 处理文件列表 - 模型文件
      if (data.model_files && Array.isArray(data.model_files) && data.model_files.length > 0) {
        fileList1.value = data.model_files.map((file, index) => ({
          uid: `model-${index}`,
          name: file.file_name || file.name || "设备模型文件",
          status: "done",
          url: file.url || file.file_url,
          response: {
            succeeded: true,
            data: {
              url: file.url || file.file_url,
              file_id: file.file_id,
              file_name: file.file_name || file.name
            }
          }
        }));
        console.log("设置模型文件:", fileList1.value);
      } else if (data.model_file || data.model_url) {
        const modelUrl = data.model_file || data.model_url;
        fileList1.value = [
          {
            uid: "1",
            name: data.model_file_name || "设备模型文件",
            status: "done",
            url: modelUrl,
            response: {
              succeeded: true,
              data: {
                url: modelUrl
              }
            }
          },
        ];
        console.log("设置模型文件:", fileList1.value);
      }

      // 处理文件列表 - 预览图片
      if (data.image_files && Array.isArray(data.image_files) && data.image_files.length > 0) {
        fileList2.value = data.image_files.map((file, index) => ({
          uid: `image-${index}`,
          name: file.file_name || file.name || "预览图片",
          status: "done",
          url: file.url || file.file_url,
          response: {
            succeeded: true,
            data: {
              url: file.url || file.file_url,
              file_id: file.file_id,
              file_name: file.file_name || file.name
            }
          }
        }));
        console.log("设置预览图片:", fileList2.value);
      } else if (data.image || data.thumb_url) {
        const imageUrl = data.image || data.thumb_url;
        fileList2.value = [
          {
            uid: "2",
            name: data.image_file_name || "预览图片",
            status: "done",
            url: imageUrl,
            response: {
              succeeded: true,
              data: {
                url: imageUrl
              }
            }
          },
        ];
        console.log("设置预览图片:", fileList2.value);
      }
    }
  } catch (error) {
    console.error("获取设备详情失败:", error);
    message.error("获取设备详情失败");
  }
};

const submitLoading = ref(false);

// 提交表单
const handleSubmit = async () => {
  try {
    submitLoading.value = true;

    let response;
    
    if (isEdit.value) {
      // 编辑模式：只提交修改的字段
      const submitData = {
        equipment_id: equipmentId.value,
        name: formState.value.name,
        equipment_category_id: formState.value.equipment_category_id,
        introduce: introduction.value,
        enabled: formState.value.status === "enabled",
        // 只在文件有变化时才提交文件URL
        ...(getImageUrl() && { thumb_url: getImageUrl() }),
        ...(getModelFileUrl() && { model_url: getModelFileUrl() }),
      };

      console.log("编辑提交数据:", submitData);
      response = await administratorApi.ExperimentEquipmentUpdate(submitData);
    } else {
      // 新增模式：使用FormData格式
      const formData = new FormData();
      
      // 添加基础字段
      formData.append('equipment_category_id', formState.value.equipment_category_id);
      formData.append('name', formState.value.name);
      formData.append('introduce', introduction.value || '');
      
      // 添加模型文件
      if (fileList1.value.length > 0) {
        fileList1.value.forEach((file, index) => {
          if (file.originFileObj) {
            // 新上传的文件
            formData.append('model_files', file.originFileObj);
          }
        });
      }
      
      // 添加预览图片文件
      if (fileList2.value.length > 0) {
        fileList2.value.forEach((file, index) => {
          if (file.originFileObj) {
            // 新上传的文件
            formData.append('image_files', file.originFileObj);
          }
        });
      }

      console.log("新增提交数据 (FormData):");
       for (let [key, value] of formData.entries()) {
         console.log(key, value);
       }
       
       // 使用特殊的API调用方式处理FormData
       response = await administratorApi.ExperimentEquipmentCreateWithFormData(formData);
    }

    if (response) {
      message.success(isEdit.value ? "更新成功" : "创建成功");
      router.back();
    } else {
      message.error(isEdit.value ? "更新失败" : "创建失败");
    }
  } catch (error) {
    console.error("提交失败:", error);
    message.error("操作失败，请重试");
  } finally {
    submitLoading.value = false;
  }
};

// 获取图片URL
const getImageUrl = () => {
  if (fileList2.value.length > 0) {
    const file = fileList2.value[0];
    // 优先使用新上传的文件URL，然后是已存在的文件URL
    return file.response?.data?.url || file.response?.url || file.url || "";
  }
  return "";
};

// 获取模型文件URL
const getModelFileUrl = () => {
  if (fileList1.value.length > 0) {
    const file = fileList1.value[0];
    // 优先使用新上传的文件URL，然后是已存在的文件URL
    return file.response?.data?.url || file.response?.url || file.url || "";
  }
  return "";
};

const resetForm = () => {
  router.back();
};
const configurationList = ref([
  {
    configurationName: "",
    configurationParameter: "",
  },
]);
const content = ref("");
const introduction = ref("");

const addDevice = () => {
  configurationList.value.push({
    configurationName: "",
    configurationParameter: "",
  });
};

const deleteDevice = (index) => {
  configurationList.value.splice(index, 1);
};
const fileList1 = ref([]);

// 自定义上传函数 - 设备模型
const customUpload1 = async (options) => {
  const { file, onSuccess, onError, onProgress } = options;

  try {
    onProgress({ percent: 50 });
    const response = await systemApi.FileUpload(file);
    console.log("模型文件上传响应:", response);

    // 适配实际的API响应格式
    if (response && response.url) {
      // 构造符合Ant Design Upload组件期望的响应格式
      const formattedResponse = {
        succeeded: true,
        data: {
          url: response.url.trim().replace(/`/g, ""), // 去除URL中的反引号和空格
          file_id: response.file_id,
          file_name: response.file_name,
          file_size: response.file_size,
          file_content_type: response.file_content_type,
        },
      };
      console.log("格式化后的响应:", formattedResponse);
      onSuccess(formattedResponse, file);
    } else {
      console.error("API响应格式错误:", response);
      onError(new Error("上传失败：响应格式错误"));
    }
  } catch (error) {
    console.error("模型文件上传失败:", error);
    onError(error);
  }
};
const equipmentOptions = ref([]);
const equipmentOptionsLoading = ref(false);
// 获取设备分类选项
const getEquipmentOptions = async (keyWords = "") => {
  try {
    equipmentOptionsLoading.value = true;
    const response = await administratorApi.EquipmentCategoryOptions({});

    console.log("设备分类选项API响应:", response?.length, "项");

    if (response) {
      equipmentOptions.value = response;
      console.log("设备分类选项加载完成:", response.length, "项");
    } else {
      console.error("获取设备分类选项失败");
      equipmentOptions.value = [];
    }
  } catch (error) {
    console.error("获取设备分类选项出错:", error);
    equipmentOptions.value = [];
  } finally {
    equipmentOptionsLoading.value = false;
  }
};
const handleChange1 = (info) => {
  const { fileList } = info;
  fileList1.value = fileList;

  const status = info.file.status;
  console.log("=== 模型文件上传状态详情 ===");
  console.log("文件状态:", status);
  console.log("文件名:", info.file.name);
  console.log("文件大小:", info.file.size);
  console.log("响应数据:", info.file.response);
  console.log("文件URL:", info.file.url);
  console.log("完整文件对象:", info.file);
  console.log("文件列表:", fileList);
  console.log("================================");

  if (status === "done") {
    // 处理上传成功的响应数据
    const response = info.file.response;
    console.log("处理上传成功响应:", response);

    if (response && response.succeeded && response.data) {
      // 更新文件信息，使用API返回的URL
      info.file.url = response.data.url;
      console.log("设置文件URL为:", response.data.url);
      message.success(`${info.file.name} 模型文件上传成功`);
    } else {
      console.error("响应格式错误:", response);
      message.error(`${info.file.name} 模型文件上传失败`);
    }
  } else if (status === "error") {
    console.error("上传错误:", info.file.error);
    message.error(`${info.file.name} 模型文件上传失败`);
  }
};

function handleDrop1(e) {
  console.log("模型文件拖拽:", e);
}

const fileList2 = ref([]);

// 自定义上传函数 - 预览图片
const customUpload2 = async (options) => {
  const { file, onSuccess, onError, onProgress } = options;

  try {
    onProgress({ percent: 50 });
    const response = await systemApi.FileUpload(file);
    console.log("预览图片上传响应:", response);

    // 适配实际的API响应格式
    if (response && response.url) {
      // 构造符合Ant Design Upload组件期望的响应格式
      const formattedResponse = {
        succeeded: true,
        data: {
          url: response.url.trim().replace(/`/g, ""), // 去除URL中的反引号和空格
          file_id: response.file_id,
          file_name: response.file_name,
          file_size: response.file_size,
          file_content_type: response.file_content_type,
        },
      };
      console.log("格式化后的响应:", formattedResponse);
      onSuccess(formattedResponse, file);
    } else {
      console.error("API响应格式错误:", response);
      onError(new Error("上传失败：响应格式错误"));
    }
  } catch (error) {
    console.error("预览图片上传失败:", error);
    onError(error);
  }
};

const handleChange2 = (info) => {
  const { fileList } = info;
  fileList2.value = fileList;

  const status = info.file.status;
  console.log("=== 预览图片上传状态详情 ===");
  console.log("文件状态:", status);
  console.log("文件名:", info.file.name);
  console.log("文件大小:", info.file.size);
  console.log("响应数据:", info.file.response);
  console.log("文件URL:", info.file.url);
  console.log("完整文件对象:", info.file);
  console.log("文件列表:", fileList);
  console.log("================================");

  if (status === "done") {
    // 处理上传成功的响应数据
    const response = info.file.response;
    console.log("处理上传成功响应:", response);

    if (response && response.succeeded && response.data) {
      // 更新文件信息，使用API返回的URL
      info.file.url = response.data.url;
      console.log("设置文件URL为:", response.data.url);
      message.success(`${info.file.name} 预览图片上传成功`);
    } else {
      console.error("响应格式错误:", response);
      message.error(`${info.file.name} 预览图片上传失败`);
    }
  } else if (status === "error") {
    console.error("上传错误:", info.file.error);
    message.error(`${info.file.name} 预览图片上传失败`);
  }
};

function handleDrop2(e) {
  console.log("预览图片拖拽:", e);
}
const rules = ref({
  name: [
    {
      required: true,
      message: "请输入设备名称",
      trigger: "blur",
    },
  ],
  equipment_category_id: [
    {
      required: true,
      message: "请选择分类",
      trigger: "change",
    },
  ],
  
});
</script>
